package cn.yh.register.hosp.service.impl;

import cn.yh.register.hosp.api.DepartmentRepository;
import cn.yh.register.hosp.service.DepartmentService;
import cn.yh.register.model.hosp.Department;
import cn.yh.register.vo.hosp.DepartmentQueryVo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    DepartmentRepository departmentRepository;

    /**
     * 保存科室信息
     * @param objectMap 科室信息
     */
    @Override
    public void saveDepartment(Map<String, Object> objectMap) {
        //转对象
        Department department = JSONObject.parseObject(JSONObject.toJSONString(objectMap), Department.class);
        //先查询科室是否存在
        Department dept = departmentRepository.findByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
        if (dept==null) {
            //不存在，新增
            department.setCreateTime(new Date());
            department.setIsDeleted(0);
        }else {//存在，修改
            department.setId(dept.getId());
            department.setCreateTime(dept.getCreateTime());
            department.setIsDeleted(dept.getIsDeleted());
        }
        department.setUpdateTime(new Date());
        departmentRepository.save(department);
    }

    /**
     * 分页查询科室列表
     * @param pageNo   当前页码
     * @param pageSize 每页条数
     * @param queryVo  查询条件
     * @return 分页数据
     */
    @Override
    public Page<Department> finDeptList(Integer pageNo, Integer pageSize, DepartmentQueryVo queryVo) {
        Department department = new Department();
        BeanUtils.copyProperties(queryVo,department);
        //匹配器
        ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true);
        //条件对象
        Example<Department> example = Example.of(department,matcher);
        //分页对象 页码从0开始
        PageRequest pageRequest = PageRequest.of(pageNo-1, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));
        //分页查询
        return departmentRepository.findAll(example, pageRequest);

    }

    /**
     * 删除科室
     * @param hoscode 医院编号
     * @param depcode 科室编号
     */
    @Override
    public void removeDepartment(String hoscode, String depcode) {
        Department department = departmentRepository.findByHoscodeAndDepcode(hoscode, depcode);
        if (department!=null) {
            departmentRepository.delete(department);
        }
    }


}
